import time

import requests
import pymysql
from pyecharts import options
from pyecharts.charts import Geo, BMap

from pyecharts.globals import GeoType
from pyecharts import options as opts

AK = "tS7IRGXa3BMj7YGHUenffOInUjTX2tOY"
webAK="qWsm3GUh6zUPhYnZ2AaxQWEKIrEUjbcM"
conn = None
def connectDB():
    global conn
    conn = pymysql.connect(host='118.25.146.226',port=3306, user="root", passwd="!@#qaz5201314")
    # 获取游标
    # cursor = conn.cursor()
    # # 创建pythonBD数据库
    # cursor.execute('CREATE DATABASE IF NOT EXISTS pythonDB DEFAULT CHARSET utf8 COLLATE utf8_general_ci;')
    # cursor.close()  # 先关闭游标
    # conn.close()  # 再关闭数据库连接

def queryDB(name):
    cursor =conn.cursor()
    cursor.execute('select * from test.location where name =\'{0}\''.format(name))
    list=[]
    while 1:
        res=cursor.fetchone()
        if res is None:
            break
        list.append(res)
    cursor.close()
    if len(list)==0:
        return None
    return list[0]
def insertDB(name,location):
    cursor = conn.cursor()
    try:
        cursor.execute("insert into test.location(name,location)values('{0}','{1}')".format(name,location))
        conn.commit()
    except Exception as e:
        pass
    cursor.close()

def get_positionFromAK(name,AK):
    url = f'http://api.map.baidu.com/geocoding/v3/?address={name}&output=json&ak={AK}'
    res = requests.get(url)
    val = res.json()
    retval = {'地址':name,'经度':val['result']['location']['lng'],'纬度':val['result']['location']['lat'],'地区标签':val['result']['level'],'是否精确查找':val['result']['precise']}
    longitude = retval['经度']
    latitude = retval['纬度']
    return(longitude,latitude)

def get_position(name):
    global AK
    cache=queryDB(name)
    if cache==None:

        location=get_positionFromAK(name,AK)
        insertDB(name,location)
        cache=queryDB(name)
    return cache

def render(addr,longitude,latitude,addrList,safeAddrList,path):
    #我的位置
    geo=BMap(init_opts=opts.InitOpts(
                      width="1920px",height="1080px"))
    g = geo.add_schema(baidu_ak=webAK,center=(longitude,latitude),is_roam=True,zoom=10)

    g.add_coordinate(addr, longitude, latitude)
    data_pair = [(addr, 1)]
    for addInfo in addrList:
        g.add_coordinate(addInfo[0],addInfo[1],addInfo[2])
        data_pair.append((addInfo[0],99))
    for addInfo in safeAddrList:
        g.add_coordinate(addInfo[0],addInfo[1],addInfo[2])
        data_pair.append((addInfo[0],1))

    g.add('', data_pair, type_=GeoType.EFFECT_SCATTER, symbol_size=5)

    g.set_series_opts(label_opts=options.LabelOpts(is_show=False))
    # #疫情的位置
    # g = geo.add_schema(maptype=addr[0:2]+"2")
    #
    # #g.add_coordinate(addr, longitude, latitude)
    # data_pair = []
    #
    # g.add('', data_pair, type_=GeoType.EFFECT_SCATTER, symbol_size=5)
    #
    # g.set_series_opts(label_opts=options.LabelOpts(is_show=False))
    g.set_global_opts(title_opts=options.TitleOpts(title="昨日疫情分布情况"),
                      visualmap_opts=opts.VisualMapOpts(   #视觉映射配置
            # pos_top="10",       #图例离顶部的距离
            # pos_left="10",     #图例离左边边框的距离
            type_ = "color",  # 映射过渡类型，可选，"color", "size"  （颜色映射还是大小映射）（重要！！！）
            #其中color参数使点的颜色随着数值进行变化，size参数使点的大小随着数值进行变化（变大变小）
            # max_ = 300,       # 指定 visualMapPiecewise 组件的最大值。
            is_piecewise=True,     #是否分段
            pieces=[            #自定义的每一段的范围，以及每一段的文字，以及每一段的特别的样式
                # {"max": 100, "min": 50, "label": ">=120", "color": "#B40404"},#label自定义的文字，color自定义的每一段的颜色
                # {"max": 49, "min": 0, "label": "90-119", "color": "#DF0101"},
                # {"max": 89, "min": 60, "label": "60-89", "color": "#F78181"},
                # {"max": 59, "min": 30, "label": "30-59", "color": "#F5A9A9"},
                # {"max": 29, "min": 1, "label": "1-29",  "color": "#FFFFCC"},
                {"value": 99, "label": '0', "color": 'red'},
                {"value": 1, "label": '0', "color": 'green'}                #专门为特定数据定义样式，例如给值为0的点定义灰色，但是0不能在上面的范围里，否则不显示定义的颜色
            ]
        )
    )

    g.render(path=path)
    print("done")
def analyzeDataBase(fileName):

    s1="居住于"
    s2="，"
    result=[]
    with open(fileName,'r',encoding="utf-8") as file:
        linelist = file.readlines()
        for line in linelist:
            simples=line.split(s2)
            for simple in simples:
                if simple.find(s1) != -1:
                    start = simple.index(s1) + len(s1)
                    line2 = simple[start:]
                    print(line2)
                    result.append(line2)
    return result
def containList(str,strList):
    for s in strList:
        if str.__contains__(s):
            return True
    return False
def analyzeDataBaseNew(fileName):
    quList=[
        "黄浦区",
        "徐汇区",
        "长宁区",
        "静安区",
        "普陀区",
        "虹口区",
        "杨浦区",
        "闵行区",
        "宝山区",
        "嘉定区",
        "浦东区",
        "金山区",
        "松江区",
        "青浦区",
        "奉贤区",
        "崇明区",
        "浦东新区"
    ]
    quTemp=None
    s2="，"
    result=[]
    with open(fileName,'r',encoding="utf-8") as file:
        linelist = file.readlines()
        for line in linelist:
            if line.__contains__("居住于") or line.__contains__("消毒") or line.__contains__("("):
                continue
            simples=line.replace("。","").replace(" ","").replace("、","").replace("\n","")
            if len(simples)<3:
                continue
            if containList(simples,quList):
                quTemp=simples
            else:
                print(quTemp+simples)
                result.append(quTemp+simples)
    return result
if __name__ == '__main__':
    connectDB()
    name="dataBase/"+time.strftime("%Y%m%d", time.localtime())
    #name="dataBase/20220409"
    addr="上海市宝山区杨行镇克山路550弄";
    locationStr=get_position(addr);
    location=eval(locationStr[1])
    baseAddrList=analyzeDataBaseNew(name+".txt")
    addrList=[]
    for baseAddr in baseAddrList:
        try:
            locStr=get_position(baseAddr);
            loc = eval(locStr[1])
            addrList.append((baseAddr,loc[0],loc[1]))
        except Exception as e:
            print(e);
            print("baseAddr  is "+str(baseAddr))
    safeAddrStrList=["宝山区杨行镇同济路1118号","锦绣申江金桥华虹创新园16栋"]
    safeAddrList=[]
    for safeAddrStr in safeAddrStrList:
        locStr=get_position(safeAddrStr);
        loc = eval(locStr[1])
        safeAddrList.append((safeAddrStr,loc[0],loc[1]))
    render(addr,location[0],location[1],addrList,safeAddrList,name+".html")
